//
//  VCMConfigViewController.m
//  CloudMonitoring
//
//  Created by TerryChe on 2016/12/20.
//  Copyright © 2016年 TerryChe. All rights reserved.
//

#import "CMConfigViewController.h"
#import <CommonCrypto/CommonDigest.h>

#import "PrefixHeader.pch"

@interface CMConfigViewController ()<UITextFieldDelegate, UIAlertViewDelegate, UITextViewDelegate, UIActionSheetDelegate>

- (IBAction)btnCreateConfigClick:(id)sender;
    
- (IBAction)btnInstallClick:(id)sender;
    
-(IBAction)btnCleanCache:(id)sender;

@property (nonatomic, strong) IBOutlet UITextField *textBusiness;

@property (nonatomic, strong) IBOutlet UITextField *textDate;

@property (nonatomic, strong) IBOutlet UILabel *lblVer;

@property (nonatomic, strong) NSString *apiUrl;
@property (nonatomic, strong) NSString *baseToken;
@property (nonatomic, strong) NSString *businessID;
@property (nonatomic, strong) NSString *businessKey;

@property (nonatomic, strong) NSString *updatePath;

@end

@implementation CMConfigViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSString *configPath = [str_cm_dir stringByAppendingPathComponent:str_cm_config];
    if ([[NSFileManager defaultManager] fileExistsAtPath:configPath]) {
        NSDictionary *configDic = [[NSDictionary alloc] initWithContentsOfFile:configPath];
        if (configDic.count > 0 && ![configDic[@"versionName"] isEqualToString:@""]) {
            self.lblVer.text = [NSString stringWithFormat:@"当前版本：%@", configDic[@"versionName"]];
        }
    }
    
    self.textBusiness.delegate = self;
    
    UIDatePicker *date = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
    date.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    date.datePickerMode = UIDatePickerModeDate;
    [date addTarget:self action:@selector(changeData:) forControlEvents:UIControlEventValueChanged];
    self.textDate.inputView = date;
    
    [self setDateText:[NSDate date]];
}

-(void)changeData:(UIDatePicker *)datePicker
{
    [self setDateText:datePicker.date];
}

-(void)setDateText:(NSDate *)date{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *data = [fmt stringFromDate:date];
    self.textDate.text = data;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [textField resignFirstResponder];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnCreateConfigClick:(id)sender{
    @try{
        if ([_textBusiness.text isEqualToString:@""]) {
            [self alertView:@"请输入商家编号"];
            return;
        }
        
        self.businessID = _textBusiness.text;
        
        NSLog(@"获取api地址");
        OPHRequest* request = [OPHRequest jsonReqeust:str_cm_api_address type:OPH_HTTP_GET];
        OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
        
        if ([response isRequestOk]) {
            NSDictionary *dic = [response excepedNSDictionaryResult];
            self.apiUrl = dic[@"apiurl"];
        }
        NSLog(@"apiUrl:%@", self.apiUrl);
        if (self.apiUrl == nil || [self.apiUrl isEqualToString:@""]) {
            [self alertView:@"获取 apiUrl 失败"];
            return;
        }
        
        if(![self.apiUrl hasPrefix:@"http://"]){
            self.apiUrl = [NSString stringWithFormat:@"http://%@", self.apiUrl];
        }
        
        NSLog(@"获取Token");
        UInt64 nowInterval = [[NSDate date] timeIntervalSince1970];
        
        NSMutableDictionary *dicParams = [[NSMutableDictionary alloc]init];
        [dicParams setObject:str_cm_appid forKey:@"appId"];
        [dicParams setObject:[NSString stringWithFormat:@"%llu", nowInterval] forKey:@"timestamp"];
        [dicParams setObject:str_cm_nonce forKey:@"nonce"];
        NSString* str = [NSString stringWithFormat:@"%@%llu%@", str_cm_appkey, nowInterval, str_cm_nonce];
        [dicParams setObject:[self sha1:str] forKey:@"signature"];
        
        NSString* url = [NSString stringWithFormat:@"%@/api/LoginToken?format=json", self.apiUrl];
        request = [OPHRequest jsonReqeust:url type:OPH_HTTP_POST params:dicParams];
        response = [[OPHNetwork sharedInstance] syncRequest:request];
        
        if ([response isRequestOk]) {
            OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
            
            if ([jsonResult isResultSuccess]) {
                self.baseToken = jsonResult.result[@"access_token"];
            }
        }
        
        NSLog(@"Token:%@", self.baseToken);
        if (self.baseToken == nil || [self.baseToken isEqualToString:@""]) {
            [self alertView:@"获取 Token 失败"];
            return;
        }
        
        if (self.apiUrl == nil || [self.apiUrl isEqualToString:@""] ||
            self.baseToken == nil || [self.baseToken isEqualToString:@""]) {
            [self alertView:@"网络连接失败，请稍后再尝试"];
            return;
        }
        
        NSLog(@"获取businessKey");
        url = [NSString stringWithFormat:@"%@/api/values/%@?access_token=%@", self.apiUrl, self.businessID, self.baseToken];
        request = [OPHRequest jsonReqeust:url type:OPH_HTTP_GET];
        response = [[OPHNetwork sharedInstance] syncRequest:request];
        
        if ([response isRequestOk]) {
            OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
            
            if ([jsonResult isResultSuccess]) {
                self.businessKey = jsonResult.result[@"merchant_appkey"];
            }
        }
        else if(response.statusCode == 500){
            [self alertView:@"商家编号错误，请重新输入"];
            return;
        }
        
        NSLog(@"businessKey:%@", self.businessKey);
        if (self.businessKey == nil || [self.businessKey isEqualToString:@""]) {
            NSLog(@"获取 businessKey 失败");
            [self alertView:@"网络连接失败，请稍后再尝试"];
            return;
        }
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:str_cm_dir]) {
            //创建文件夹
            [[NSFileManager defaultManager] createDirectoryAtPath:str_cm_dir withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
        [dateFormat setDateFormat:@"yyyy-MM-dd"];//设定时间格式,这里可以设置成自己需要的格式
        NSDate *date = [dateFormat dateFromString:self.textDate.text];
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:self.apiUrl forKey:@"address"];
        [dic setObject:self.businessKey forKey:@"appKey"];
        [dic setObject:self.businessID forKey:@"appID"];
        [dic setObject:@"" forKey:@"nonce"];
        [dic setObject:@(60) forKey:@"sleep"];
        [dic setObject:@(50) forKey:@"batchCount"];
        if (date != nil) {
            [dic setObject:@([date timeIntervalSince1970]) forKey:@"beginDate"];
        }
        
        NSString *configPath = [str_cm_dir stringByAppendingPathComponent:str_cm_config];
        [dic writeToFile:configPath atomically:YES];
        
        NSLog(@"配置文件生成成功:%@", configPath);
        [self alertView:@"配置文件生成成功，请重启手机生效"];
        
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
    @catch (NSException *exception) {
        [self alertView:@"网络连接失败，请稍后再尝试"];
    }
}

- (IBAction)btnInstallClick:(id)sender
{
    if(iosVerion < 8.0) {
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"重启手机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertview show];
    } else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"重启手机" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"重启手机");
            int result = reboot(2);
            NSLog(@"重启完成 %d", result);
        }];
        [alertController addAction:okAction];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)alertView:(NSString *)text
{
    if(iosVerion < 8.0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:text delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
    } else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:text preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex != alertView.cancelButtonIndex){
        NSString *message = alertView.message;
        if ([message isEqualToString:@"重启手机"]) {
            NSLog(@"重启手机");
            int result = reboot(2);
            NSLog(@"重启完成 %d", result);
        }
    }
}

-(void)btnCleanCache:(id)sender {
    if(iosVerion < 8.0) {
        UIActionSheet *actionsheet= [[UIActionSheet alloc] initWithTitle:@"重传数据" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"好友资料&聊天信息", @"好友资料", @"聊天信息" , nil];
        // 显示
        [actionsheet showInView:self.view];
    }
    else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction *allAction = [UIAlertAction actionWithTitle:@"好友资料&聊天" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self deleteCacheWithFriend:true AndMsg:true];
            }];
        [alertController addAction:allAction];
        
        UIAlertAction *friendAction = [UIAlertAction actionWithTitle:@"好友资料" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self deleteCacheWithFriend:true AndMsg:false];
        }];
        [alertController addAction:friendAction];
        
        UIAlertAction *msgAction = [UIAlertAction actionWithTitle:@"聊天信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self deleteCacheWithFriend:false AndMsg:true];
        }];
        [alertController addAction:msgAction];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:cancelAction];

        [self presentViewController:alertController animated:YES completion:nil];
    }
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"好友资料&聊天信息"]) {
        [self deleteCacheWithFriend:true AndMsg:true];
    }
    else if ([title isEqualToString:@"好友资料"]) {
        [self deleteCacheWithFriend:true AndMsg:false];
    }
    else if ([title isEqualToString:@"聊天信息"]) {
        [self deleteCacheWithFriend:false AndMsg:true];
    }
}

-(void) deleteCacheWithFriend:(bool) friend AndMsg:(bool) msg {
    [SVProgressHUD showWithStatus:nil];
    NSString *userPath = [str_cm_dir stringByAppendingPathComponent:str_cm_user];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:userPath];
    for (NSString *name in data.allValues) {
        NSString *userFolder = [str_cm_dir stringByAppendingPathComponent:name];
        if (friend) {
            [[NSFileManager defaultManager] removeItemAtPath:[userFolder stringByAppendingPathComponent:@"friend.plist"] error:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[userFolder stringByAppendingPathComponent:@"chatroom.plist"] error:nil];
        }
        
        if (msg) {
            [[NSFileManager defaultManager] removeItemAtPath:[userFolder stringByAppendingPathComponent:@"chatmsg.plist"] error:nil];
        }
    }
    [SVProgressHUD showSuccessWithStatus:@"删除成功！"];
}

//sha1加密方式
- (NSString *) sha1:(NSString *)input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

@end
